<template>
  <div class="app-container" v-loading.fullscreen="fileLoading"  element-loading-text="生成报告中...">
    <div class="filter-container search_Top">
      <div class="search_input_list" ref="searchHeight" :style="{height: inputMore.setHeight}">
        <div class="filter-item">
          <el-date-picker v-model="searchParam.startTime" placeholder="送检开始时间"
                          size="mini"
                          format="yyyy-MM-dd"
                          value-format="yyyy-MM-dd"
                          type="date"
                          style="width: 140px;">
          </el-date-picker>
          <span class="date_splite"></span>
          <el-date-picker v-model="searchParam.endTime" placeholder="送检结束时间"
                          size="mini"
                          format="yyyy-MM-dd"
                          value-format="yyyy-MM-dd"
                          type="date"
                          style="width: 140px;">
          </el-date-picker>
        </div>
        <div class="filter-item">
          <el-input clearable v-model="searchParam.sampleCode" placeholder="检验单号"
                    size="mini"
                    @keyup.enter.native="getList"/>
        </div>
        <div class="filter-item">
          <el-input clearable v-model="searchParam.userName" placeholder="申请人"
                    size="mini"
                    @keyup.enter.native="getList"/>
        </div>
        <div class="filter-item">
          <el-input clearable v-model="searchParam.materialName" placeholder="样品名称"
                    size="mini"
                    @keyup.enter.native="getList"/>
        </div>
        <div class="filter-item">
          <el-input clearable v-model="searchParam.sampleNum" placeholder="样品批号"
                    size="mini"
                    @keyup.enter.native="getList"/>
        </div>
        <div class="filter-item">
          <el-select v-model="searchParam.materialTypeId" placeholder="样品规格"
                     size="mini"
                     clearable>
            <el-option v-for="item in codeItemMap.type"
                       :key="item.id"
                       :label="item.itemName"
                       :value="item.id"/>
          </el-select>
        </div>
        <div class="filter-item">
          <el-select v-model="searchParam.checkStatus" placeholder="流程状态"
                     size="mini"
                     clearable>
            <el-option v-for="item in statusMap"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value"/>
          </el-select>
        </div>
        <div class="filter-item">
          <el-input clearable v-model="searchParam.materialCode" placeholder="物料编码"
                    size="mini"
                    @keyup.enter.native="getList"/>
        </div>
        <div class="filter-item">
          <el-select v-model="searchParam.locationId" placeholder="送样地点"
                     size="mini"
                     clearable>
            <el-option v-for="item in codeItemMap.location"
                       :key="item.id"
                       :label="item.itemName"
                       :value="item.id"/>
          </el-select>
        </div>
        <div class="filter-item">
          <el-select v-model="searchParam.sampleTypeId" placeholder="样品规模"
                     size="mini"
                     clearable>
            <el-option v-for="item in codeItemMap.scope"
                       :key="item.id"
                       :label="item.itemName"
                       :value="item.id"/>
          </el-select>

        </div>
        <div class="filter-item">
          <el-select v-model="searchParam.materialGradeId" placeholder="样品等级"
                     size="mini"
                     clearable>
            <el-option v-for="item in codeItemMap.grade"
                       :key="item.id"
                       :label="item.itemName"
                       :value="item.id"/>
          </el-select>
        </div>

      </div>
      <div class="filter-item filter-item-btn-search search_bt_list">
        <span class="gosearch" @click="searchSample">搜索</span>
        <span class="clears" @click="clearList">清除</span>
      </div>
      <div class="inputmore" @click="changeMore()" v-show="inputMore.showMore">
        <span v-if="inputMore.isMore">更多搜索 <i class="el-icon-arrow-down"></i></span>
        <span v-if="!inputMore.isMore">收起 <i class="el-icon-arrow-up"></i></span>
        <div class="triangle-bottomleft"></div>
        <div class="triangle-bottomright"></div>
      </div>
    </div>
    <div class="tab-container">
      <el-tabs style="margin-top:25px;" type="border-card" v-model="currentTab" @tab-click="tabClick">
        <el-tab-pane name="mySend" v-if="hasRole('my:send')">
          <span slot="label">我的送检</span>
          <div class="app-my-task-container">
            <div class="table_base_bt">
              <el-button class="filter-btn-item" v-if="hasRole('my:send:add')"
                         size="mini"
                         type="primary"
                         icon="el-icon-edit"
                         @click="addSend">
                新增
              </el-button>
              <el-button class="filter-btn-item" v-if="hasRole('my:send:del')"
                         size="mini"
                         type="danger"
                         icon="el-icon-delete"
                         @click="batchDelete">
                删除
              </el-button>
              <el-button class="filter-btn-item same-contrast" v-if="hasRole('my:send:contrast')"
                         size="mini"
                         type="green"
                         @click="sameContrast">
                同样对比
              </el-button>
            </div>
            <drug-table :backCount="backCount" @getSelection="getSelection" @getBackData="getList"
                        :isMultipleSelection="true" :tableData="tableData" :tableLoading="tableLoading"
                        :tableHeader="tableHeader" :option="option">
              <template slot-scope="props" slot="operate">
                <div>
                  <label @click="handleEditData(props.rowData)" v-if="hasRole('my:send:see')"
                         class="table-view" style="cursor: pointer;">
                    查看
                  </label>
                  <label @click="generateRecord(props.rowData)"
                         v-if="props.rowData.checkStatus == '5' && hasRole('my:send:report')"
                         class="table-view" style="cursor: pointer;">
                    · &nbsp;报告
                  </label>
                </div>
              </template>
            </drug-table>
          </div>
        </el-tab-pane>
        <el-tab-pane name="deptSend" v-if="hasRole('dept:send')">
          <span slot="label">部门送检</span>
          <dept-send ref="deptSendRef" @generateRecord="generateRecord" v-if="loadTab.deptSend"></dept-send>
        </el-tab-pane>
        <el-tab-pane name="allSend" v-if="hasRole('all:send')">
          <span slot="label">所有送检</span>
          <all-send ref="allSendRef"  @generateRecord="generateRecord" v-if="loadTab.allSend"></all-send>
        </el-tab-pane>
      </el-tabs>
    </div>

    <send-edit ></send-edit>
    <send-see ></send-see>
    <same-contrast></same-contrast>
    <form action="/drug/file/downloadFile" method="post"
          style="display: none;" ref="downloadFile">
      <input name="path" :value="downPath"/>
    </form>
  </div>
</template>

<script>
  import waves from '@/views/directive/waves' // waves directive
  import {formatDate} from '@/utils/formatDate'
  import drugTable from "@/components/table/index";
  import sendEdit from "./dialog/sendEdit"
  import sendSee from "./dialog/sendSee"
  import sameContrast from "./dialog/sameContrast"
  import {getToken} from '@/utils/auth' // 验权
  import deptSend from './deptSendTask'
  import allSend from './allSendTask'

  export default {
    components: {drugTable, sendEdit, sendSee, sameContrast, deptSend, allSend},
    directives: {waves},
    data() {
      return {
        inputMore: {isMore: true, showMore: true, liConHeight: 36, setHeight: 36,},
        tableData: [],
        tableHeader: [],
        tableLoading: true,
        fileLoading: false,
        option: {showOperate: true},
        statusMap: [
          {label: "待领检", value: "0"},
          {label: "未送样", value: "1"},
          {label: "检测中", value: "2"},
          {label: "复检", value: "3"},
          {label: "拒绝", value: "4"},
          {label: "完成", value: "5"}
        ],
        searchParam: {
          sampleCode: "",
          userName: "",
          sampleNum: "",
          startTime: "",
          endTime: "",
          materialName: "",
          materialGradeId: "",
          checkStatus: "",
          materialCode: "",
          locationId: "",
          sampleTypeId: "",
          materialTypeId: "",
        },
        detailData: {},
        operateType: "add",

        selectChoice: [],

        backCount: 0,
        codeItemMap: {location: [], type: [], dept: [], grade: [], scope: []},
        downPath: "",

        currentTab: "",

        loadTab:{mySend:false,deptSend:false,allSend:false}
      }
    },
    mounted() {
      let self = this;
      let user = JSON.parse(getToken());
      this.user = user;
      this.initPickerTime();
      self.changeMore();
      self.getCurrentTab();
      self.getAllList();
      self.getItemCode();
      self.$eventBus.$on("updateSampleList", function () {
        for (let key in self.searchParam) {
          self.searchParam[key] = "";
        }
        self.getList(0, 20);
      })
    },
    methods: {
      searchSample(){
        if(this.currentTab == 'mySend'){
          this.getList(0, 20);
        }else if(this.currentTab == 'deptSend'){
          this.$refs.deptSendRef.searchList(this.searchParam);
        }else if(this.currentTab == 'allSend'){
          this.$refs.allSendRef.searchList(this.searchParam);
        }
      },

      tabClick(tab, event) {
        let self = this;
        let tabName = tab.name;
        if (!self.loadTab[tabName]) {
          self.loadTab[tabName] = true;
          self.$nextTick(() => {
            if (tabName == 'mySend') {
              this.getList(0, 20);
            }
            if (tabName == 'deptSend') {
              this.$refs.deptSendRef.searchList(this.searchParam);
            }
            if (tabName == 'allSend') {
              this.$refs.allSendRef.searchList(this.searchParam);
            }
          })
        }
      },


      getAllList() {
        if (this.hasRole('my:send')) {
          this.loadTab.mySend = true;
          this.getList(0, 20);
        }else if (this.hasRole('dept:send')) {
          this.loadTab.deptSend = true;
          this.$refs.deptSendRef.searchList(this.searchParam);
        }else if (this.hasRole('all:send')) {
          this.loadTab.allSend = true;
          this.$refs.allSendRef.searchList(this.searchParam);
        }
      },
      getCurrentTab() {
        if (this.hasRole('my:send')) {
          this.currentTab = 'mySend';
        } else if (this.hasRole('dept:send')) {
          this.currentTab = 'deptSend';
        } else if (this.hasRole('all:send')) {
          this.currentTab = 'allSend';
        }
      },
      initPickerTime() {
        let nowDate = formatDate(new Date(), "yyyy-MM-dd");
        let beforeMoth = new Date().getTime() - 30 * 24 * 3600 * 1000;
        let mouth = formatDate(new Date(beforeMoth), "yyyy-MM-dd");
        this.searchParam.startTime = mouth;
        this.searchParam.endTime = nowDate;
      },
      changeMore() {
        let liCon = this.$refs.searchHeight;
        let height = liCon.offsetHeight;
        if (height == this.inputMore.liConHeight) {
          this.inputMore.isMore = false;
          liCon.style.height = 'auto';
          height = liCon.offsetHeight;
          this.inputMore.setHeight = height + 'px'
        } else {
          this.inputMore.isMore = true;
          this.inputMore.setHeight = this.inputMore.liConHeight + 'px'
        }
        if (this.inputMore.setHeight == '36px' && !this.inputMore.isMore) {
          this.inputMore.showMore = false
        }
      },
      generateRecord(row) {
        let self = this;
        let cellList = [];
        cellList.push(this.getCell("物料编码", 0, "EEEEEE"));
        cellList.push(this.getCell(row.materialCode, 0));
        cellList.push(this.getCell("检 验 号", 0, "EEEEEE"));
        cellList.push(this.getCell(row.sampleCode, 0));
        cellList.push(this.getCellCode(row.sampleCode, 0));

        cellList.push(this.getCell("样品名称", 1, "EEEEEE"));
        cellList.push(this.getCell(row.materialName, 1));


        cellList.push(this.getCell("样品规格", 2, "EEEEEE"));
        cellList.push(this.getCell(row.materialType, 2));
        cellList.push(this.getCell("样品规模", 2, "EEEEEE"));
        cellList.push(this.getCell(row.sampleTypeName, 2));

        cellList.push(this.getCell("样品等级", 3, "EEEEEE"));
        cellList.push(this.getCell(row.materialGrade, 3));
        cellList.push(this.getCell("申 请 人", 3, "EEEEEE"));
        cellList.push(this.getCell(row.userName, 3));

        cellList.push(this.getCell("样品批号", 4, "EEEEEE"));
        cellList.push(this.getCell(row.sampleNum, 4));
        cellList.push(this.getCell("申请时间", 4, "EEEEEE"));
        cellList.push(this.getCell(row.createTimeFt, 4));
        let splitRow = [];
        splitRow.push("4,3,4,0");
        splitRow.push("2,0,1,1");
        splitRow.push("3,0,1,1");
        splitRow.push("4,0,3,1");
        let day = formatDate(new Date(), "yyyy-MM-dd hh:mm:ss");
        let param = {
          id: row.id,
          sampleCode: row.sampleCode,
          title: "分析测试中心检验原始记录",
          // printPerson: "打印人：" + this.user.userName + " " + day,
          printPerson: "",
          graphWordList: [
            {
              title: "检样信息",
              colIndex: 5,
              cellList: [],
              splitRow: []
            },
            {
              title: "",
              colIndex: 5,
              cellList: [],
              splitRow: []
            },
            {
              title: "",
              colIndex: 4,
              cellList: [],
              splitRow: []
            }
          ]
        };
        param.graphWordList[0].cellList = cellList;
        param.graphWordList[0].splitRow = splitRow;

        let cellList1 = [];
        cellList1.push(this.getCell("检项", 0, "EEEEEE", 1800));
        cellList1.push(this.getCell("质量标准", 0, "EEEEEE"));
        cellList1.push(this.getCell("检验结果", 0, "EEEEEE"));
        cellList1.push(this.getCell("备注", 0, "EEEEEE", 1000));
        cellList1.push(this.getCell("工时", 0, "EEEEEE", 800));

        param.graphWordList[1].cellList = cellList1;

        let cellList2 = [];
        cellList2.push(this.getCell("审批状态", 0, "EEEEEE"));
        cellList2.push(this.getCell("", 0));
        cellList2.push(this.getCell("审批人", 0, "EEEEEE"));
        cellList2.push(this.getCell("", 0));

        cellList2.push(this.getCell("审批时间", 1, "EEEEEE"));
        cellList2.push(this.getCell("审批时间", 1));
        cellList2.push(this.getCell("审批意见", 1, "EEEEEE"));
        cellList2.push(this.getCell("审批意见", 1));

        param.graphWordList[2].cellList = cellList2;
        self.fileLoading = true;
        self.$http({
          url: "/drug/sample/querySamplePath",
          method: "post",
          data: JSON.stringify(param),
          dataType: 'json',
          contentType: "application/json",
        }).then(resp => {
          if (resp.success) {
            self.downPath = resp.result;
            self.$nextTick(() => {
              self.$refs.downloadFile.submit();
            });
          }
          self.fileLoading = false;
        });
      },
      getCell(text, index, backGround, width) {
        let cell = {
          text: text,
          fontSize: 11,
          family: "黑体",
          index: index ? index : 0,
          width: width ? width : 0
        };
        if (backGround) {
          cell.backGround = "EEEEEE"
        }
        return cell;
      },

      getCellCode(text) {
        let cell = {
          code: text,
          index: 0
        };
        return cell;
      },


      getList(startIndex, pageRow) {
        let self = this;
        self.tableLoading = true;
        let searchParam = Object.assign({}, this.searchParam);
        if (searchParam.endTime) {
          searchParam.endTime = searchParam.endTime + " 23:59:59";
        }
        if (this.user.type != 1) {
          searchParam.userId = this.user.id;
        }
        let start = typeof startIndex == "number" ? startIndex : 0;
        let total = typeof pageRow == "number" ? pageRow : 20;
        searchParam.startIndex = start;
        searchParam.totalPage = total;
        self.$http({
          url: "/drug/sample/querySampleList",
          method: "post",
          params: searchParam
        }).then(resp => {
          if (resp.success) {
            self.tableLoading = false;
            self.tableData = resp.result;
            self.backCount = self.tableData.length > 0 ? self.tableData[0].count : 0;
            self.tableHeader = [
              {"columnName": "sampleCode", "coloumNameCn": "检验单号"},
              {"columnName": "userName", "coloumNameCn": "申请人", "width": "70px"},
              {"columnName": "createTimeSecondFt", "coloumNameCn": "送检时间"},
              {"columnName": "materialName", "coloumNameCn": "样品名称"},
              {"columnName": "sampleNum", "coloumNameCn": "样品批号"},
              {"columnName": "materialCode", "coloumNameCn": "物料编码"},
              {"columnName": "materialType", "coloumNameCn": "样品规格"},
              {"columnName": "materialGrade", "coloumNameCn": "样品等级"},
              // {"columnName": "sampleTypeName", "coloumNameCn": "样品规模"},
              {"columnName": "locationName", "coloumNameCn": "送样地点"},
              {"columnName": "checkStatusCn", "coloumNameCn": "流程状态"}];
            self.option.showOperate = true;
          }
        });
      },
      clearList() {
        let self = this;
        for (let key in self.searchParam) {
          self.searchParam[key] = "";
        }
        self.getList()
      },
      getSelection(val) {
        this.selectChoice = val;
      },
      handleEditData(rowData) {
        this.detailData = Object.assign({}, rowData);
        this.detailData.materialTypeId = this.detailData.materialType;
        this.detailData.materialGradeId = this.detailData.materialGrade;
        this.$eventBus.$emit("openSendSee", this.detailData);
      },
      addSend() {
        this.detailData = {
          id: "",
          saveTmp: false,
          sampleCode: "",
          locationId: "",
          finalProduct: "",
          sampleTypeId: "",
          materialName: "",
          materialCode: "",
        };
        this.operateType = "add";
        this.$eventBus.$emit("openSendEdit", this.detailData, this.operateType, this.codeItemMap);
      },

      batchDelete() {
        let param = {ids: [], sampleCode: ""};
        let sampleCodes = [];
        for (let data of this.selectChoice) {
          param.ids.push(data.id);
          sampleCodes.push(data.sampleCode);
        }
        param.sampleCode = sampleCodes.join(",");
        param.userName = this.$store.getters.userName;
        this.deleteRow(param);
      },
      deleteRow(param) {
        let self = this;
        if (!param || param.ids.length < 1) {
          self.$notify({
            title: '提示',
            message: "至少选择一条记录！",
            type: 'warning'
          });
          return
        }
        self.$confirm('确定删除该信息？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          self.$http({
            url: "/drug/sample/batchDeleteSample",
            method: "post",
            data: JSON.stringify(param),
            dataType: 'json',
            contentType: "application/json",
          }).then(resp => {
            if (resp.success) {
              self.getList(0, 20);
              self.$notify({
                title: '提示',
                message: "删除成功！",
                type: 'success'
              });
              return
            }
            self.$notify({
              title: '提示',
              message: "操作失败，请联系管理员！",
              type: 'error'
            });
          });
        });
      },

      getItemCode() {
        let self = this;
        self.codeItemMap = {location: [], type: [], dept: [], grade: [], scope: []};
        self.$http({
          url: "/drug/codeItem/queryCodeItemList",
          method: "post",
        }).then(resp => {
          if (resp.success) {
            for (let data of resp.result) {
              if (self.codeItemMap.hasOwnProperty(data.itemCode)) {
                self.codeItemMap[data.itemCode].push(data);
              }
            }
          }
        });
      },
      sameContrast() {
        let choiceIds = [];
        if (this.selectChoice.length == 0) {
          this.$notify({
            title: '提示',
            message: "请选择对比项！",
            type: 'warning'
          });
          return;
        }
        if (this.selectChoice.length == 1) {
          this.$notify({
            title: '提示',
            message: "请至少选择两项对比！",
            type: 'warning'
          });
          return;
        }
        let materialName = "";
        for (let data of this.selectChoice) {
          if (!materialName) {
            materialName = data.materialName;
          }
          if (materialName != data.materialName) {
            this.$notify({
              title: '提示',
              message: "请选择相同样品名称对比！",
              type: 'warning'
            });
            return;
          }
          choiceIds.push(data.sampleCode);
        }
        // if(!this.searchParam.startTime||!this.searchParam.endTime){
        //   this.$notify({
        //     title: '提示',
        //     message: "请选择时间！",
        //     type: 'warning'
        //   });
        //   return;
        // }
        this.$eventBus.$emit("openSameContrast", materialName, this.searchParam, choiceIds);
      }
    },
  }
</script>


<style lang="scss" scoped>
  .el-form-no {
    text-align: right;
    font-size: 18px;
    color: #cb0000;
  }

  .el-dialog .el-button--primary {
    background-color: #2e827f;
    border-color: #2e827f;
    border-radius: 3px;
    padding: 5px 10px;
  }
</style>
